package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.exception.GlobleException;
import cn.itsource.ymcc.service.IPayOrderService;
import cn.itsource.ymcc.to.PlaceCourseOrderTo;
import com.alibaba.fastjson.JSON;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
//课程下单，保存支付单
@RocketMQMessageListener(topic = BaseConstants.OrderMQ.TOPIC_COURSE_ORDER
        ,selectorExpression=BaseConstants.OrderMQ.TAGS_PAY_ORDER
        ,consumerGroup = "service-pay-consumer")
public class SavePayOrderConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt message) {
        String json = new String(message.getBody(), CharsetUtil.UTF_8);

        log.info("保存支付订单 {}",json);
        PlaceCourseOrderTo placeCourseOrderTo = JSON.parseObject(json, PlaceCourseOrderTo.class);

        //重复下单处理
        synchronized (placeCourseOrderTo.getOrderNo()){
            PayOrder payOrder = payOrderService.selectByOrderNo(placeCourseOrderTo.getOrderNo());
            if(payOrder == null){
                payOrderService.savePayOrder(placeCourseOrderTo);
                log.info("保存支付单成功");
            }
        }

    }
}
